package Server.controller.mobile;

import Plug.operLog.OperLog;
import Plug.result.RetResponse;
import Plug.result.RetResult;
import Server.dao.*;
import Server.entity.*;
import Server.tool.*;
import com.alipay.api.internal.util.AlipaySignature;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("mobile/ShopController")
public class MobileShopController {
    @Autowired
    private ShopClassDao shopClassDao;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private ShopCarDao shopCarDao;
    @Autowired
    private ShopOrderDao shopOrderDao;
    @Autowired
    private UsersDao usersDao;
    @Autowired
    private ShopSpecDao shopSpecDao;
    @Autowired
    private ShopOrderItemDao shopOrderItemDao;
    @Autowired
    private ShopOrderSaleDao shopOrderSaleDao;
    @Autowired
    private UsersSaleDao usersSaleDao;
    /*
    * 获得商品分类
    *
    * */
    @RequestMapping("GetClass")
    public RetResult GetClass(){
        JSONArray jsonArray  =  new JSONArray();
        List<ShopClass> classList = shopClassDao.findByStatus(ShopClass.Status.ING);
        for(ShopClass cs:classList){
            JSONObject jo = new JSONObject();
            jo.put("uuid",cs.getUuid());
            jo.put("name",cs.getName());
            List<Map<String, String>> list2 = EntityUtils.listConvert(shopDao.findByTypeGroupBy(cs));
            jo.put("child",list2);
            jsonArray.add(jo);
        }
        return RetResponse.makeOKRsp(jsonArray);
    }
    /*
     * 清空购物车
     *
     * */
    @Transactional
    @RequestMapping("ClearCar")
    public RetResult ClearCar(){
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        fspuser=usersDao.findByUuid(fspuser.getUuid());
        shopCarDao.deleteByUsers(fspuser);
        return RetResponse.makeOKRsp();
    }
    /*
    *
    * 我的订单
    *
    * */
    @RequestMapping("GetMyOrder")
    public RetResult GetMyOrder(@RequestBody JSONObject jsonObject){
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        ExampleMatcher matcher = ExampleMatcher.matching();

        ShopOrder shopOrder = (ShopOrder) BeanToJson.jsonTobean(jsonObject.getJSONObject("common").toString(), ShopOrder.class);

        Example<ShopOrder> example = Example.of(shopOrder, matcher);
        fspuser=usersDao.findByUuid(fspuser.getUuid());
        shopOrder.setUsers(fspuser);
        int page = Integer.parseInt(jsonObject.getString("page")) - 1;
        int size = Integer.parseInt(jsonObject.getString("limit"));
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "uuid");

        Page<ShopOrder> userlist = shopOrderDao.findAll(example, pageable);
        return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
    }
    /*
    *
    * 已收货
    *
    * */
    @RequestMapping("OrderEnd")
    public RetResult OrderEnd(@RequestBody ShopOrder shopOrder){
        shopOrder=shopOrderDao.findByUuid(shopOrder.getUuid());
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        fspuser=usersDao.findByUuid(fspuser.getUuid());
        if(!fspuser.equals(shopOrder.getUsers())){
            return RetResponse.makeErrRsp("请操作自己的订单");
        }
        shopOrder.setStatus(ShopOrder.Status.END);
        shopOrderDao.save(shopOrder);
        return RetResponse.makeOKRsp();
    }
    /*
     *
     * 取消订单
     *
     * */
    @RequestMapping("OrderCall")
    public RetResult OrderCall(@RequestBody ShopOrder shopOrder){
        String note  =shopOrder.getNote();
        shopOrder=shopOrderDao.findByUuid(shopOrder.getUuid());
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        fspuser=usersDao.findByUuid(fspuser.getUuid());
        if(!fspuser.equals(shopOrder.getUsers())){
            return RetResponse.makeErrRsp("请操作自己的订单");
        }
        if(!shopOrder.getStatus().equals(ShopOrder.Status.NO)){
            return RetResponse.makeOKRsp("已付款!不能取消");
        }
        shopOrder.setStatus(ShopOrder.Status.CALL);
        shopOrder.setNote(note);
        shopOrderDao.save(shopOrder);
       /* *//*
        *
        * 库存加入
        *
        * *//*
        ShopSpec spec = shopOrder.getShopSpec();
        spec.setRepertory(spec.getRepertory()+shopOrder.getCount());
        shopSpecDao.save(spec);*/
        List<ShopOrderItem> specs = shopOrderItemDao.findByShopOrder(shopOrder);
        for(ShopOrderItem item:specs){
            item.getShopSpec().setRepertory(item.getShopSpec().getRepertory()+item.getCount());
            shopSpecDao.save(item.getShopSpec());
        }
        /*
        *
        * 优惠券还原
        *
        * */
        List<ShopOrderSale> sales = shopOrderSaleDao.findByShopOrder(shopOrder);
        for(ShopOrderSale item:sales){
            item.getUsersSale().setStatus(UsersSale.Status.ING);
            usersSaleDao.save(item.getUsersSale());
        }
        return RetResponse.makeOKRsp();
    }
    /*
     *
     * 订单退货
     *
     * */
    @RequestMapping("OrderQuit")
    public RetResult OrderQuit(@RequestBody ShopOrder shopOrder){
        String note  =shopOrder.getNote();
        shopOrder=shopOrderDao.findByUuid(shopOrder.getUuid());
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        fspuser=usersDao.findByUuid(fspuser.getUuid());
        if(!fspuser.equals(shopOrder.getUsers())){
            return RetResponse.makeErrRsp("请操作自己的订单");
        }
        if(shopOrder.getStatus().equals(ShopOrder.Status.CALL)&&shopOrder.getStatus().equals(ShopOrder.Status.NO)&&shopOrder.getStatus().equals(ShopOrder.Status.QUIT)){
            return RetResponse.makeErrRsp("当前状态不能退货");
        }
        shopOrder.setNote(note);
        shopOrder.setStatus(ShopOrder.Status.QUIT);
        shopOrderDao.save(shopOrder);
        return RetResponse.makeOKRsp();
    }
    @OperLog("订单留言")
    @RequestMapping("OrderSpack")
    public RetResult OrderSpack(@RequestBody ShopOrder shopOrder){
        ShopOrder entity = shopOrderDao.findByUuid(shopOrder.getUuid());
        entity.setSpack(shopOrder.getSpack());
        shopOrderDao.save(entity);
        return RetResponse.makeOKRsp();
    }
    @RequestMapping("Pay")
    @OperLog("订单付款")
    public RetResult Pay(@RequestBody ShopOrder shopOrder){
        shopOrder=shopOrderDao.findByUuid(shopOrder.getUuid());
        if(!shopOrder.getStatus().equals(ShopOrder.Status.NO)){
            return RetResponse.makeErrRsp("当前状态不允许付款");
        }else{
            return RetResponse.makeOKRsp(AliPayE.pay(shopOrder.getMoney(),"旺财商城产品购买",shopOrder.getUuid()));
        }
    }
    @Autowired
    private AlibbDao alibbDao;
    @RequestMapping("albbbank")
    public void albbbank(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //这个是签名类型 sign参数已经帮我们删除掉了，在这里我们要把签名类型删除掉
        params.remove("sign_type");
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AliPayConfig.alipay_public_key, AliPayConfig.charset, AliPayConfig.sign_type); //调用SDK验证签名
        if (signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            Alibb alibb = new Alibb();
            alibb.setStatus(trade_status);
            alibb.setMoney(new BigDecimal(total_amount));
            alibb.setOrderId(out_trade_no);
            alibb.setJyId(trade_no);
            alibbDao.save(alibb);
            if (trade_status.equals("TRADE_SUCCESS")) {
                //log.info("支付成功---------->");
                PrintWriter out;
                try {
                    out = response.getWriter();
                    response.reset();
                    //需要给支付宝返回success
                    out.print("success");
                    out.flush();
                    out.close();
                    out = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    ShopOrder shopOrder = shopOrderDao.findByUuid(out_trade_no);
                    shopOrder.setStatus(ShopOrder.Status.YES);
                    shopOrderDao.save(shopOrder);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 修改订单状态，改为 支付成功，已付款; 同时新增支付流水

            } else {
                System.out.println("没有处理支付宝回调业务，支付宝交易状态");
                //log.error("没有处理支付宝回调业务，支付宝交易状态：{},params:{}", trade_status, params);
            }
        } else {
            System.out.println("失败");
            //log.error("失败");
        }
    }
}
